import "ol/ol.css";
import * as control from "ol/control";
import { Map, View } from "ol/index";
import ImageLayer from "ol/layer/Image";
import Projection from "ol/proj/Projection";
import Static from "ol/source/ImageStatic";
import { getCenter } from "ol/extent";

import onlineImageMap from "../img/map.jpg";
let map;
// 单个图片需要设置地图大小和图片大小相同
const extent = [0, 0, 1024, 968];
const projection = new Projection({
  code: "xkcd-image",
  units: "pixels",
  extent: extent,
});
let view = new View({
  projection: projection,
  center: getCenter(extent),
  zoom: 2,
  maxZoom: 4,
});

export const initMap = (mapDom) => {
  map = new Map({
    target: mapDom,
    controls: control.defaults({
      attribution: false,
      zoom: true,
      rotate: true,
    }),
    view: view,
  });

  const imageLayer = new ImageLayer({
    source: new Static({
      attributions: '© <a href="https://xkcd.com/license.html">xkcd</a>',
      // url: 'https://imgs.xkcd.com/comics/online_communities.png',远程图片地址可以直接使用url地址
      url: onlineImageMap, // 项目中的资源图片也可以直接使用
      projection: projection,
      imageExtent: extent,
    }),
  });

  map.addLayer(imageLayer);
};

/**
 * @use 地图单击事件
 * @param {*} cb 回调
 */
export const singleClickFun = (cb) => {
  map.on("singleclick", (e) => {
    // resetMap(); //复位可直接使用
    cb(e);
  });
};

/**
 * @use 平移动画
 * @param {*} position 指定坐标点 [106.5, 29.5],
 * @param {*} duraion 动画持续时间
 */
export const panTo = (position, duraion) => {
  view.animate({
    center: position,
    duration: duraion != null ? duraion : 1500,
  });
};
